$(function () {

    // 初始化右上角的登录按钮的显示
    var curUser = JSON.parse($.cookie('User'));
    var curCar = JSON.parse($.cookie('Car'));
    if (curUser == null) {
        $('#nav .user a:eq(0)').text('登录').attr('href', './login.html');
        $('#nav .user a:eq(1)').text('购物车').attr('href', './login.html');
    } else {
        $('#nav .user a:eq(0)').text(curUser.username).attr('href', '#')
        $('#nav .user a:eq(1)').text(`购物车`).attr('href', './car.html')
    }
    // 购物车按钮判断
    $('#nav .user a:eq(1)').on('click', function (e) {
        e.preventDefault();
        if ($(this).attr('href') == './login.html') {
            layer.alert(
                '您还没有登录请先登录',
                {
                    icon: 0,
                    shadeClose: true,
                    title: '消息',
                },
                function () {
                    location.href = '../login.html'
                },
            );
        } else {
            location.href = '../car.html'
        }
    })

    // 初始化页面
    init();

    // 根据传过来的id得到对象的商品对象
    function getGoods(id) {
        return shoes[(id - 1)];
    }
    function init() {
        $('#main').html('');
        if (curCar.length == 0) {
            $('#main').append(`<h2>您的购物车</h2>
            <div class="Empty">
                <span>您的购物车是空的</span>
                <a href="./shop.html">继续浏览添加商品</a>
            </div>`)
        } else {
            $('#main').append(`<h2>您的购物车</h2>`)
            $('#main').append(`<table>
            <thead>
                <tr>
                    <th><input type="checkbox" class="allBox"></th>
                    <th></th>
                    <th></th>
                    <th>价格</th>
                    <th>数量</th>
                    <th>总价</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
        `);
		
            var totalPrice = 0;
            var str = '';
            $.each(curCar, function (index, item) {
                // shoes对象
                var thisGood = getGoods(item.id);
                // 购物车中的对象
                item.isToPay = false;
                // thisGood.isToPay = false;
                // 判断是否已经去结算了
                str = `<tr shoesId="${thisGood.id}">
                <td><input type="checkbox" class="itemBox"></td>
                <td>
                    <a href="../detail.html?id=${thisGood.id}">
                        <img src="${thisGood.src}" alt="">
                    </a>
                </td>
                <td>
                    <span>${thisGood.name}</span>
                    <a href="javascript:;" dataId="${item.id}">删除</a>
                </td>
                <td>${thisGood.price}</td>
                <td>
                    <div>
                        <span class="decrease">-</span>
                        <span class="choose" dataId="${item.id}">${item.choose}</span>
                        <span class="increase">+</span>
                    </div>
                </td>
                <td class="thePrice">$${item.price}</td>
            </tr>`

                $('tbody').append(str)
                str = '';
                totalPrice = totalPrice + +item.price
            })
            $('table').after(`<div class="tablefooter">
                <p>小计 <span>$${totalPrice}</span></p>
                <p>结账时计算的运费和税费</p>
                <p><a href="javascript:;">结算($0)</a></p>
            </div>`)

        }
    }


    // 移除某一商品(删除一整个商品)
    $('tbody tr td:eq(2)').on('click', 'a', function () {
        // 要删除元素的下标
        var id = $(this).attr('dataId');
        var index = -1;
        var totalPrice = +$('.tablefooter span').text().substring(1);
        $.each(curCar, function (i, item) {
            if (item.id == id) {
                index = i;
                totalPrice = totalPrice - item.price;
            }
        })
        curCar.splice(index, 1);
        $('.tablefooter span').text(`$${totalPrice}`)
        $(this).parent().parent().remove()
        if (curCar.length == 0) {
            init();
        }
        $.cookie('Car', JSON.stringify(curCar));
    })

    // 修改数量
    $('tbody tr div').on('click', 'span', function () {
        // 获取一下数量
        var $number = $(this).parent().find('.choose');
        var number = +$number.text();
        // 获取当前被点击的商品
        var clickId = $number.attr('dataId');
        // 小计
        var $xiaoji = $(this).parent().parent().parent().find('td:last');
        var xiaoji = +$xiaoji.text().substring(1);
        // 总价
        var $totalPrice = $('.tablefooter span');
        var totalPrice = +$totalPrice.text().substring(1);
        // 获取单价
        var $danjia = $(this).parent().parent().parent().find('td:eq(3)');
        var danjia = $danjia.text().substring(1);

        var $a = $(this).parent().parent().parent().find('a');
        // 减少逻辑
        if ($(this).attr('class') == 'decrease') {
            number--;
            if (number == 0) {
                $a.click();
            } else {
                $number.text(number);
                totalPrice = totalPrice - danjia
                xiaoji = xiaoji - danjia
                $totalPrice.text(`$${totalPrice}`);
                $xiaoji.text(`$${xiaoji}`);
                $.each(curCar, function (index, item) {
                    if (item.id == clickId) {
                        item.choose = number;
                        item.price = xiaoji;
                    }
                })
            }
            $.cookie('Car', JSON.stringify(curCar));
        }
        // 增加逻辑
        if ($(this).attr('class') == 'increase') {
            number++;
            $number.text(number);
            totalPrice = +totalPrice + +danjia
            xiaoji = +xiaoji + +danjia
            $totalPrice.text(`$${totalPrice}`);
            $xiaoji.text(`$${xiaoji}`);
            $.each(curCar, function (index, item) {
                if (item.id == clickId) {
                    item.choose = number;
                    item.price = xiaoji;
                }
            })
            $.cookie('Car', JSON.stringify(curCar));
        }
    })

    // 全选单选
    var allBox = $('.allBox');
    var itemBox = $('.itemBox');
    // 全选的时候用全选的状态改单选盒子
    allBox.on("click", function () {
        itemBox.prop('checked', $(this).prop('checked'));
        if (allBox.prop('checked')) {
            $('.tablefooter a').text(`结算(${$('.tablefooter span').text()})`)
            $('tbody tr').addClass('check');
        } else {
            $('.tablefooter a').text(`结算($0)`)
            $('tbody tr').removeClass('check');
        }

    });
    // 单选
    itemBox.on("click", function () {
        // 直接对未选中盒子的个数取反
        allBox.prop('checked', !$('.itemBox:not(:checked)').length);
        if ($(this).prop('checked')) {
            $(this).parent().parent().addClass('check');
        } else {
            $(this).parent().parent().removeClass('check');
        }
        var theCheckBox = $('tbody tr[class="check"]');
        var totalPrice = 0;
        $.each(theCheckBox, function (i, item) {
            price = +$(item).find('.thePrice').text().substring(1);
            totalPrice += price;
        })
        $('.tablefooter a').text(`结算($${totalPrice})`)
    });


    // 结算
    $('.tablefooter a').on('click', function () {
        if (!$('tbody tr[class="check"]').length) {
            layer.msg('请选择要结算的商品', { icon: 2, time: 1000 });
            return;
        } else {
            $.each($('tbody tr[class="check"]'), function (i, item) {
                var shoesId = $(item).attr('shoesId');

                for (var j = 0; j < curCar.length; j++) {
                    if (curCar[j].id == shoesId) {
                        console.log(111);
                        curCar[j].isToPay = true;
                    }
                }
            })
            $.cookie('Car', JSON.stringify(curCar));
            location.href = '../pay.html'
        }
    })
})